package com.ruoyi.web.controller.yf;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.YfGlobal;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.yf.domain.YfClientVersion;
import com.ruoyi.yf.service.IYfClientVersionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 客户端 版本更新Controller
 * 
 * @author XiaoYi...
 * @date 2020-04-08
 * d36d2283-4f3f-4acd-a0b8-71868a0fa083
 */
@Controller
@Configuration
@RequestMapping("/yf/version")
public class YfClientVersionController extends BaseController
{
    private String prefix = "yf/version";

    @Autowired
    private IYfClientVersionService yfClientVersionService;

    @Autowired
    private ISysDictDataService dictDataService;



    @RequiresPermissions("yf:version:view")
    @GetMapping()
    public String version()
    {
        return prefix + "/version";
    }

    /**
     * 查询客户端 版本更新列表
     * 8ece09a0-e23f-4b82-a9ae-58c3efc9239a
     */
    @RequiresPermissions("yf:version:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YfClientVersion yfClientVersion){
        startPage();
        List<YfClientVersion> list = yfClientVersionService.selectYfClientVersionList(yfClientVersion);
        return getDataTable(list);
    }

    /**
     * 导出客户端 版本更新列表
     * 4c8ec0d5-e73a-4fd7-8ee9-a052df8025fc
     */
    @RequiresPermissions("yf:version:export")
    @Log(title = "客户端 版本更新", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YfClientVersion yfClientVersion)
    {
        List<YfClientVersion> list = yfClientVersionService.selectYfClientVersionList(yfClientVersion);
        ExcelUtil<YfClientVersion> util = new ExcelUtil<YfClientVersion>(YfClientVersion.class);
        return util.exportExcel(list, "version");
    }

    /**
     * 新增客户端 版本更新
     * 66b6d569-de7a-4d48-abea-b0b9eb12743c
     */
    @GetMapping("/add")
    public String add(ModelMap mmap){
        // 从字典表按dicttype查询dictdata
        mmap.put("apptypes", dictDataService.selectDictDataByType("YF_CLIENT_UPDATE_TYPE"));
        return prefix + "/add";
    }

    /**
     * 新增保存客户端 版本更新
     * 4842deff-7955-496b-bd99-eb906b74a4e7
     */
    @RequiresPermissions("yf:version:add")
    @Log(title = "客户端 版本更新", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YfClientVersion yfClientVersion,
                              @RequestParam(value="file",required = false ) MultipartFile file) {
        // 保存apk
        if( file != null && !file.isEmpty() ){
            String apkPath = saveApk(file,yfClientVersion.getCode());
            yfClientVersion.setUrl(apkPath);
        }else{
            logger.debug(" ------ 未选择apk文件！  " );
        }
        yfClientVersion.setCreateId(ShiroUtils.getUserId());
        return toAjax(yfClientVersionService.insertYfClientVersion(yfClientVersion));
    }


    // 保存apk
    //d6a26051-084e-4a56-b503-e1a273d33ead
    public String saveApk(MultipartFile file,String version){
        String imgPath = "";
        String fileNames = "newAPP" + version + "_" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) ;
        try {
            imgPath = FileUploadUtils.upload( Global.getProfile(),
                    "/" + YfGlobal.getApkPath() + "/" + new SimpleDateFormat("yyyy-MM").format(new Date()),
                    file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, fileNames );
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidExtensionException e) {
            e.printStackTrace();
        }
        return imgPath;
    }

    // 删除旧apk
    //d0958434-5393-41f3-b9af-f82904765ffc
    public void deleteApk(String apkPath){
//        int index = apkPath.indexOf(uploadPath_url);
//        if(index >= 0) {
//            apkPath = apkPath.substring(index + uploadPath_url.length());
//        }
        try {
            apkPath = UriUtils.decode(apkPath, "UTF-8");
            apkPath = Global.getProfile() + apkPath.replace("","profile/") ;
                    logger.debug("----------旧地址： " + apkPath );
            File file_old=new File(apkPath);
            if(file_old.exists()){
                file_old.delete();
            }
        } catch (Exception e) {
        }
    }




    /**
     * 修改客户端 版本更新
     * 33b5d48b-9ea5-4896-b5a7-555918fa8363
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        YfClientVersion yfClientVersion = yfClientVersionService.selectYfClientVersionById(id);
        mmap.put("yfClientVersion", yfClientVersion);
        // 从字典表按dicttype查询dictdata
        List<SysDictData> dictList = dictDataService.selectDictDataByType("YF_CLIENT_UPDATE_TYPE");
        // 已有的更新类型
        if(!StringUtils.isEmpty(yfClientVersion.getType())){
            String[] dictZu = yfClientVersion.getType().split(",");
            for (int i = 0; i <dictZu.length; i++) {
                for (int j = 0; j < dictList.size(); j++) {
                    if( dictZu[i].equals(dictList.get(j).getDictValue()) ){
                        dictList.get(j).setFlag(true);
                        break;
                    }
                }
            }
        }
        mmap.put("apptypes", dictList );
        return prefix + "/edit";
    }

    /**
     * 修改保存客户端 版本更新
     * dc571953-52cc-4de9-84a4-a477fd868eb8
     */
    @RequiresPermissions("yf:version:edit")
    @Log(title = "客户端 版本更新", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YfClientVersion yfClientVersion,
                               @RequestParam(value="file",required = false ) MultipartFile file) {
        // 如果更新了apk，则保存apk
        if( file != null && !file.isEmpty() ){
            String apkPath = saveApk(file,yfClientVersion.getCode());
            // 删除旧apk
            if(!StringUtils.isEmpty(yfClientVersion.getUrl())){
                deleteApk(yfClientVersion.getUrl());
            }
            yfClientVersion.setUrl(apkPath);
        }else{
            logger.debug(" ------ 未选择apk文件！  " );
        }
        yfClientVersion.setUpdateId(ShiroUtils.getUserId());
        return toAjax(yfClientVersionService.updateYfClientVersion(yfClientVersion));
    }

    /**
     * 删除客户端 版本更新
     * 4ac0f8cc-1d86-427d-9af2-df49d7f62806
     */
    @RequiresPermissions("yf:version:remove")
    @Log(title = "客户端 版本更新", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        return toAjax(yfClientVersionService.deleteYfClientVersionByIds(ids));
    }


}
